package com.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.store.common.Result;
import com.store.dto.StockAdjustRequest;
import com.store.dto.StockQueryRequest;
import com.store.service.StockService;
import com.store.util.JwtUtil;
import com.store.vo.StockRecordVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 库存管理控制器
 * 
 * @author Store Team
 */
@RestController
@RequestMapping("/stock")
@RequiredArgsConstructor
public class StockController {

    private final StockService stockService;
    private final JwtUtil jwtUtil;

    /**
     * 调整库存（管理员权限）
     */
    @PostMapping("/adjust")
    public Result<Void> adjustStock(@Valid @RequestBody StockAdjustRequest request, 
                                    HttpServletRequest httpRequest) {
        try {
            // 从token获取操作人ID
            String token = httpRequest.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long operatorId = jwtUtil.getUserIdFromToken(token);
            
            stockService.adjustStock(request, operatorId);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询库存记录
     */
    @PostMapping("/records")
    public Result<IPage<StockRecordVO>> getStockRecords(@RequestBody StockQueryRequest request) {
        try {
            IPage<StockRecordVO> page = stockService.getStockRecords(request);
            return Result.success("查询成功", page);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 入库（管理员权限）
     */
    @PostMapping("/in")
    public Result<Void> stockIn(@RequestBody StockAdjustRequest request,
                                HttpServletRequest httpRequest) {
        try {
            // 从token获取操作人ID
            String token = httpRequest.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long operatorId = jwtUtil.getUserIdFromToken(token);

            // 入库只能是正数
            if (request.getAdjustQuantity() <= 0) {
                return Result.error("入库数量必须大于0");
            }

            stockService.stockIn(request.getProductId(), request.getAdjustQuantity(), 
                               operatorId, request.getRemark());
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

}

